import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/user/login.vue'
import home from '../views/home/home.vue'
import movie from '../views/movie/movie.vue'
import qa from '../views/qa/qa.vue'
import user from '../views/user/user.vue'
import notFound from '../views/notFound/notFound.vue'
import edit from '../views/user/edit.vue'

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'home',
    path: '/home',
    component: home,
    meta: { showTab: true }
  },
  {
    name: 'movie',
    path: '/movie',
    component: movie,
    meta: { showTab: true }
  },
  {
    name: 'qa',
    path: '/qa',
    component: qa,
    meta: { showTab: true }
  },
  {
    name: 'user',
    path: '/user',
    component: user,
    meta: {
      showTab: true,
      isLogin: true
    }
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name:'notfound',
    path: '/notfound',
    component: notFound,
    meta: { showTab: true }
  },
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '*',
    redirect:"/notfound"
  }
]

// 原理是将VueRouter的原型链上的push方法中的   throw(err)[捕获错误] 的方法,让其不抛出错误
const toHtml=VueRouter.prototype.push
// console.log(toHtml);
VueRouter.prototype.push = function push(location) {
  return toHtml.call(this, location).catch(err =>err)
}

const router = new VueRouter({
  routes
})

import {getToken} from '@/utils/token.js'

router.beforeEach((to, from, next) => {
  // console.log(getToken());
  // console.log("to:",to);
  // console.log('from:',from);
  // console.log('next:', next);
  // 此处判断,原因为:可能用户直接进入主页切换至用户,实际上没有登录
  if (to.meta.isLogin && !getToken()) {
    next({path:'/login'})
  } else {
    next()
  }
})

export default router
